<!--
 * @Author       : Hejh(3010733382@qq.com)
 * @Version      : V1.0
 * @Date         : 2024-01-29 20:04:48
 * @Description  : 存储管理
-->
<template>
  <div
    class="bg-lightColor storage-con p-3 rounded"
    v-if="editModel === 'view'"
  >
    <n-grid
      x-gap="12"
      :cols="1"
      class="mb-2"
      v-permission="[PERMISSIONS.STORAGE_EDIT]"
    >
      <n-gi>
        <n-button
          type="primary"
          size="small"
          class="!text-[13px]"
          @click="handleToAdd"
        >
          <SvgIcon
            icon="zengjiatianjiajiahao"
            color="#badeff"
            class="mr-1"
          ></SvgIcon>
          新增
        </n-button>
      </n-gi>
    </n-grid>

    <n-divider class="!my-2" />

    <div class="flex flex-wrap" v-loading="loading">
      <storage-card
        v-for="item in data"
        :key="item.id"
        :storage-origin="item"
        @select-change="handleSelectChange"
      ></storage-card>
    </div>
  </div>

  <!-- 添加或者更新面板 -->
  <create-and-update-storage
    :is-modify="editModel === 'update'"
    :storage-res="curStorage"
    @change-storage="handleAddAndUpdateStorage"
    v-else
    @back-view="editModel = 'view'"
  >
  </create-and-update-storage>
</template>

<script setup lang="ts">
import { useMessage, NButton, useDialog } from 'naive-ui'
import {
  createStorageOrigin,
  delStorageOrigin,
  getStorageOriginByPage,
  setDefaultStorageOrigin,
  updateStorageOrigin
} from '@/api/storageOrigin'
import type {
  StorageOriginCreateReq,
  StorageOriginRes,
  StorageOriginUpdateReq
} from '@/types/storageOrigin'
import { PERMISSIONS } from '@/constants/permission'
import { load } from '@/utils/loading'
import SvgIcon from '@/components/SvgIcon/index.vue'
import PicValidCode from '@/components/PicValidCode/index.vue'
import StorageCard from './components/StorageCard.vue'
import CreateAndUpdateStorage from './components/CreateAndUpdateStorage.vue'

const message = useMessage()
const dialog = useDialog()

const data = ref<StorageOriginRes[]>([])
const pageInfo = reactive({
  page: 1,
  pageSize: 999
})
const loading = ref(false)

// 获取存储源列表
const loadStorageOrigins = () => {
  loading.value = true
  getStorageOriginByPage(pageInfo)
    .then((res) => {
      data.value = res.data.items
    })
    .catch(console.error)
    .finally(() => {
      loading.value = false
    })
}

onMounted(() => {
  loadStorageOrigins()
})

// 去添加存储源
const handleToAdd = () => {
  editModel.value = 'create'
}

const curStorage = ref<StorageOriginRes>()
// 去编辑存储源
const handleToUpdate = (row: StorageOriginRes) => {
  curStorage.value = row
  editModel.value = 'update'
}

// 去设置默认存储源
const handleToSetDefaultOrigin = (storageOriginId: string) => {
  load.show()
  setDefaultStorageOrigin(storageOriginId)
    .then(() => {
      message.success('设置默认存储源成功')
      afterOpt()
    })
    .catch(console.error)
    .finally(() => {
      load.hide()
    })
}

// 去删除存储源
const handleToDel = (row: StorageOriginRes) => {
  let dialogObj = dialog.warning({
    title: '你确定要删除该存储源吗？',
    class: '!w-[768px]',
    content: () =>
      h(
        PicValidCode,
        {
          showCloseIcon: false,
          class: '!w-full',
          onOnFinish: (picCode: string) => {
            load.show()
            delStorageOrigin([row.id], picCode)
              .then(() => {
                message.success('删除存储源成功')
                afterOpt()
                dialogObj.destroy()
              })
              .catch(console.error)
              .finally(() => {
                load.hide()
              })
          }
        },
        []
      )
  })
}

const handleSelectChange = (type: string, data: StorageOriginRes) => {
  if (type === 'remove') {
    // 移除存储源
    handleToDel(data)
  } else if (type === 'modify') {
    handleToUpdate(data)
  } else if (type === 'setDefault') {
    // 设为默认存储源
    handleToSetDefaultOrigin(data.id)
  } else if (type === 'moveData') {
    // 数据迁移
  }
}

// ================================= 存储源新增和更新逻辑===============================================
const editModel = ref<'create' | 'update' | 'view'>('view')

const handleAddStorage = (data: StorageOriginCreateReq) => {
  load.show()
  createStorageOrigin(data)
    .then(() => {
      message.success('添加存储源成功')
      afterOpt()
    })
    .catch(console.error)
    .finally(() => {
      load.hide()
    })
}

const handleUpdateStorage = (data: StorageOriginUpdateReq) => {
  load.show()
  updateStorageOrigin(data)
    .then(() => {
      message.success('更新存储源成功')
      afterOpt()
    })
    .catch(console.error)
    .finally(() => {
      load.hide()
    })
}

const handleAddAndUpdateStorage = (
  type: number,
  data: StorageOriginUpdateReq
) => {
  if (type === 1) {
    handleUpdateStorage(data)
  } else {
    handleAddStorage(data)
  }
}

const afterOpt = () => {
  loadStorageOrigins()
  editModel.value = 'view'
}
</script>

<style scoped lang="scss">
.storage-con {
  font-size: 13px;
}
</style>
